﻿using OestsCommon.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace OestsDataBase
{
    public static class TaskDAL
    {
        /// <summary>
        /// 创建任务表
        /// teacher_id:0代表内建任务，其他代表教师建的任务
        /// </summary>
        public static void CreateTable()
        {
            string sqlCheck = "if object_id( 'T_Task') is not null select 1 else select 0";
            if ((int)SqlHelper.ExecuteScalar(sqlCheck) == 0)
            {
                string sqlCreacte = @"CREATE TABLE T_Task (id bigint identity(1,1) primary key ,code int not null,name NVARCHAR(MAX) not null,
project_id bigint not null,defaulttime int not null,defaultscore int,teacher_id int not null,multiplayer int not null,detail NVARCHAR(MAX))";

                SqlHelper.ExecuteNonQuery(sqlCreacte);
            }
        }

        /// <summary>
        /// 获取项目中可实训的任务
        /// </summary>
        /// <param name="projectID"></param>
        /// <returns></returns>
        private static List<TaskModel> GetTrainTasksByProject(int projectID)
        {
            List<TaskModel> tasks = new List<TaskModel>();
            foreach (TaskModel item in GetTasksByProject(projectID))
            {
                if (item.isTrain)
                {
                    item.StepScore = "";
                    tasks.Add(item);

                }
            }
            return tasks;

        }
        public static List<TaskModel> GetTasksByProject(int projectID)
        {
            string strSql = "select * from [T_Task_" + projectID+"]";
            return GetData(strSql);
        }
        /// <summary>
        /// 获取项目中随机数目的考试任务集
        /// </summary>
        /// <param name="projectID"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static List<TaskModel> GetRandomTasks(int projectID, int count)
        {
            List<TaskModel> list = GetTrainTasksByProject(projectID);
            if (list == null || list.Count == 0) return null;

            List<TaskModel> newList = GetRandomList(list, count);

            return newList;
        }
        public static List<TaskModel> GetRandomList(List<TaskModel> taskList, int count)
        {
            if (taskList.Count < count)
            {
                return taskList;
            }
            Random random = new Random();

            List<int> tempList = new List<int>();
            List<TaskModel> newList = new List<TaskModel>();
            int temp = 0;
            for (int i = 0; i < count; i++)
            {
                temp = random.Next(taskList.Count);//将产生的随机数作为被抽list的索引
                if (!tempList.Contains(temp))
                {
                    tempList.Add(temp);
                    newList.Add(taskList[temp]);
                }
                else
                {
                    i--;
                }
            }
            return newList;
        }


        public static TaskModel GetData(int projectId, string taskName)
        {
            string strSql = "select * from [T_Task_" + projectId + "] where name = " + taskName;
            List<TaskModel> list = GetData(strSql);
            if (list == null) return null;
            if (list.Count > 0)
                return GetData(strSql)[0];
            return null;
        }


        public static TaskModel GetTaskById(int projectID, int taskId)
        {
            string strSql = string.Format("select * from [T_Task_{0}] where id = {1} ", projectID.ToString(), taskId);
            List<TaskModel> list = GetData(strSql);
            if (list == null) return null;
            if (list.Count > 0)
                return list[0];
            return null;
        }

        public static List<TaskModel> GetTaskListByIDList(int projectID, List<int> idList)
        {
            string idStr = "";
            foreach (var item in idList)
            {
                idStr += idStr + ",";
            }
            idStr = idStr.Substring(0, idStr.Length - 1);

            string sql = string.Format("select * from [T_Task_{0}] where id in ({1}) ", projectID, idStr);
            List<TaskModel> list = new List<TaskModel>();
            DataTable dt = SqlHelper.ExecuteDataTable(sql);
            if (dt == null) { return null; }
            foreach (DataRow dr in dt.Rows)
            {
                TaskModel s = ReadData(dr);
                list.Add(s);
            }
            return list;

        }

        public static List<TaskModel> GetAllProjectTask()
        {
            List<string> listTable = SqlHelper.GetTableListByType("T_Task_");
            List<TaskModel> listAllData = new List<TaskModel>();
            foreach (var item in listTable)
            {
                List<TaskModel> list = GetDataByTableName(item);
                if (list != null)
                {
                    listAllData.AddRange(list);

                }
            }
            return listAllData;
        }

        private static List<TaskModel> GetDataByTableName(string tabelName)
        {
            string strSql = string.Format("select * from {0} ", tabelName);
            List<TaskModel> list = new List<TaskModel>();
            DataTable dt = SqlHelper.ExecuteDataTable(strSql);
            if (dt == null) { return null; }
            foreach (DataRow dr in dt.Rows)
            {
                TaskModel s = ReadData(dr);
                list.Add(s);
            }
            return list;
        }


        private static List<TaskModel> GetData(string sql)
        {
            List<TaskModel> list = new List<TaskModel>();
            DataTable dt = SqlHelper.ExecuteDataTable(sql);
            if (dt == null) { return null; }
            foreach (DataRow dr in dt.Rows)
            {
                TaskModel s = ReadData(dr);
                list.Add(s);
            }
            return list;
        }

        public static TaskModel ReadData(DataRow dr)
        {
            TaskModel t = new TaskModel
            {
                Id = Int32.Parse(dr["id"].ToString()),
                Shift = Int32.Parse(dr["shift"].ToString()),
                TeacherId = Int32.Parse(dr["teacher_id"].ToString()),
                Name = dr["name"].ToString(),
                ProjectId = Int32.Parse(dr["project_id"].ToString()),
                Detail = dr["detail"].ToString(),
                DefaultTime = Int32.Parse(dr["defaulttime"].ToString()),
                SetTime = dr["settime"].Equals(DBNull.Value) ? Int32.Parse(dr["defaulttime"].ToString()) : Int32.Parse(dr["settime"].ToString()),
                DefaultScore = dr["defaultscore"].Equals(DBNull.Value) ? 0 : Int32.Parse(dr["defaultscore"].ToString()),
                MultiPlayer = Int32.Parse(dr["multiplayer"].ToString()),
                isTrain = (bool)dr["isTrain"],
                StandardFlow = dr["standardFlow"].Equals(DBNull.Value) ? " " : dr["standardFlow"].ToString()
            };
            return t;
        }

        public static int Add(int projectID, TaskModel task)
        {
            string strSql = string.Format("insert into T_Task_" + projectID + @"(shift, name,   project_id,     detail,     defaulttime,    defaultscore, teacher_id)
                                                          values({0},'{1}',     {2},            '{3}',          {4},           {5},                {6});SELECT @@Identity",
                                                            task.Shift, task.Name, task.ProjectId, task.Detail, task.DefaultTime, task.DefaultScore, task.TeacherId);
            object obj = SqlHelper.ExecuteScalar(strSql);
            return Int32.Parse(obj.ToString());
        }

        public static int Delete(int projectID, int id)
        {
            string strSql = string.Format("delete from T_Task_" + projectID + " where id = @id");
            int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", id));
            return n;
        }

        ///lym 0923 add
        ///教员设置实训的时间
        public static bool SetTaskTime(int projectid, int taskid, int settime)
        {
            string strSql = string.Format("update T_Task_" + projectid.ToString() + " set settime ={0}  where id =@id", settime);
            int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", taskid));
            if (n != 0)
                return true;
            return false;
        }
        /// <summary>
        /// 将项目中所有任务的实训时间设置为默认时间
        /// </summary>
        /// <param name="projectid"></param>
        /// <returns></returns>

        public static bool SetAllTaskDefaultTime(int projectid)
        {
            string strSql = string.Format("update T_Task_" + projectid.ToString() + " set settime = defaulttime ");
            int n = SqlHelper.ExecuteNonQuery(strSql);
            if (n != 0)
            {
                return true;
            }
            return true;
        }
        /// <summary>
        /// 重新设置默认时间
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="taskid"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        public static bool ResetTaskDefaultTime(int projectid, int taskid, int time)
        {
            string strSql = string.Format("update T_Task_" + projectid.ToString() + " set defaulttime ={0}  where id =@id", time);
            int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", taskid));
            if (n != 0)
                return true;
            return false;
        }

    }
}
